<?php

class Login extends MY_Controller{
	private $isLoggedIn;
    function __construct(){
    	parent::__construct();
    }
    function index(){
    	// Set title, maincontent and load view with loginform
    	$data['title'] = "Projekt";
    	if($this->isLoggedIn() == FALSE){
    		$this->load->view('loginform');
    	}
    	else{
    		$this->load->view('logoutform');
    	}
    	$this->load->view('includes/footer');
    	//$this->load->view('includes/template', $data);
    }
    function loginValidation(){
    	// Load formvalidation-library
		$this->load->library('form_validation');
		// Set validation rules
    	$this->form_validation->set_rules(USERNAME, 'Username', 'trim|required|min_length[6]');
		$this->form_validation->set_rules(PASSWORD, 'Password', 'trim|required|min_length[6]|max_length[32]');
    	if($this->form_validation->run() == FALSE){
			// If input is not valid reload 
			$this->index();
		}
		else{
			// Load userhandler
    		$this->load->model('loginhandler');
			$username = $this->input->post(USERNAME);
			$password = $this->input->post(PASSWORD);
			$rememberMe = $this->input->post(REMEMBER_ME);
    		$login = $this->loginhandler->doLogin($username, $password);
    		if($login){
    			// If user checked 'remember me'-checkbox - set cookie
    			if($rememberMe == REMEMBER_ME){
    				// Set cookie
    				$this->setLoginCookie($username, $password);
    			}
       			//If login is valid -  go to firstpage   
    			redirect('/');
    		}
    		else{
    			// If login input is not valid set errormessage and refresh page
    			$this->session->set_flashdata('loginerror', "Incorrect username and/or password. $username $password");
    			redirect('/login');
    		}
		}	
    }
    function logout(){
    	// Logout and reload
    	$this->load->model('loginhandler');
 		$login = $this->loginhandler->doLogout();
 		$this->unsetLoginCookie();
 		redirect('/');
    }
    function setLoginCookie($username, $password){
		$this->load->helper('cookie');
		$userCookie = array(
			 'name'   => USERNAME,
             'value'  => $username,
             'expire' => time()+86500
		);
		$passCookie = array(
		     'name'   => IS_LOGGED_IN,
             'value'  => TRUE,
             'expire' => time()+86500
        );
        set_cookie($userCookie);
        set_cookie($passCookie);
    }
    function unsetLoginCookie(){
    	$this->load->helper('cookie');
    	delete_cookie(USERNAME);
    	delete_cookie(IS_LOGGED_IN);
    }
}
